package com.ruben.jwtdemo.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.ruben.jwtdemo.constant.UserConstant;
import com.ruben.jwtdemo.pojo.User;
import com.ruben.jwtdemo.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @ClassName: UserController
 * @Description:
 * @Date: 2020/8/6 19:56
 * *
 * @author: achao<achao1441470436 @ gmail.com>
 * @version: 1.0
 * @since: JDK 1.8
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private HttpServletRequest httpServletRequest;
    @Resource
    private UserService userService;

    /**
     * 登录
     *
     * @param param 参数为Json格式的User对象{"username":"","password":""}
     * @return 返回json格式的map
     */
    @PostMapping("login")
    public R login(@RequestBody User param) {
        // 登录校验用户名密码
        User user = userService.validateUser(param);
        if (user == null) {
            return R.failed("用户名或密码错误");
        }
        // 生成token(在每个请求头里加上，用于判断用户登录状态)
        String token = userService.createToken(user, UserConstant.TOKEN_EXPIRE_TIME);
        // 生成refreshToken（用于在用户token过期情况下刷新token）
        String refreshToken = userService.createToken(user, UserConstant.REFRESH_TOKEN_EXPIRE_TIME);
        HashMap<Object, Object> data = new HashMap<>(4);
        data.put("token", token);
        data.put("refreshToken", refreshToken);
        return R.ok(data);
    }

    /**
     * 刷新token
     *
     * @param refreshToken
     * @return
     */
    @GetMapping("refreshToken")
    public R refreshToken(String refreshToken) {
        return userService.refreshToken(refreshToken);
    }

    /**
     * 注销
     *
     * @return
     */
    @GetMapping("logout")
    public R logout() {
        String token = userService.getToken(httpServletRequest);
        if (StringUtils.isNotBlank(token)) {
            // 如果有token，则注销
            userService.logout(token);
        }
        return R.ok("已注销");
    }

    /**
     * 测试接口，无实际意义
     *
     * @param word
     * @return
     */
    @GetMapping("say/{word}")
    public R speak(@PathVariable String word) {
        return R.ok(word);
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    @PostMapping("register")
    public R register(@RequestBody User user) {
        User localUser = userService.getUserByUsername(user.getUsername());
        if (localUser != null) {
            return R.failed("用户名已被注册");
        }
        // 注册
        String errorMsg = userService.register(user);
        if (StringUtils.isNotBlank(errorMsg)) {
            return R.failed(errorMsg);
        }
        return R.ok("注册成功");
    }

}
